package p0;

import java.util.*;
import java.util.stream.Collectors;

public class Leetcode_49 {

    private short[] ss = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101};

    private long hash(String s) {
        long l = s.length() > 0 ? ss[(int) s.charAt(0) - 'a'] : 1;
        for (int i = 1; i < s.length(); i++) {
            l *= ss[(int) s.charAt(i) - 'a'];
        }
        return l;
    }

    public List<List<String>> groupAnagrams(String[] strs) {
//        return new ArrayList<>(Arrays.stream(strs).collect(Collectors.groupingBy(this::hash)).values());
        List<List<String>> ans = new ArrayList<>();
        Map<Long, Integer> hashIndexMap = new HashMap<>();
        int size = 0;
        for (String str : strs) {
            long hash = hash(str);
            List<String> list;
            if (hashIndexMap.containsKey(hash)) {
                int index = hashIndexMap.get(hash);
                list = ans.get(index);
            } else {
                list = new ArrayList<>();
                ans.add(list);
                hashIndexMap.put(hash, size++);
            }
            list.add(str);
        }
        return ans;
    }

    public static void main(String[] args) {
        Leetcode_49 l = new Leetcode_49();
        System.out.println(l.groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}));
        System.out.println(l.groupAnagrams(new String[]{"ac", "c"}));
    }
}
